package com.ruoyi.project.museums.controller;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.museums.domain.Message;
import com.ruoyi.project.museums.domain.Question;
import com.ruoyi.project.museums.domain.Sentence;
import com.ruoyi.project.museums.domain.UserAnswer;
import com.ruoyi.project.museums.service.IMessageService;
import com.ruoyi.project.museums.service.IQuestionService;
import com.ruoyi.project.museums.service.ISentenceService;
import com.ruoyi.project.museums.service.IUserAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @ClassName UserAnswerController
 * @Description 用户回答Controller
 * @Version 1.0
 */
@RestController
@RequestMapping("/museums/userAnswer")
public class UserAnswerController extends BaseController {
    @Autowired
    private IUserAnswerService userAnswerService;

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private ISentenceService sentenceService;

    /**
     * 查询用户回答列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserAnswer userAnswer)
    {
        startPage();
        List<UserAnswer> list = userAnswerService.selectUserAnswerList(userAnswer);
        return getDataTable(list);
    }

    /**
     * 查询用户留言列表
     */
    @GetMapping("/messageList")
    public AjaxResult messagelist(Message message)
    {
        List<Message> list = messageService.selectMessageList(message);

        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("userAnswer", list);
        return ajaxResult;
    }

    @Anonymous
    @ResponseBody
    @RequestMapping(value ="/messageList",method = RequestMethod.POST)
    public JSONObject getMessagelist(HttpServletRequest request, HttpServletResponse response){
        Message message  = new Message();
        List<Message> list = messageService.selectMessageList(message);

        JSONObject json1  = new JSONObject();
        JSONObject json  = new JSONObject();
        json1.put("notelist",list);
        json.put("list",json1);
        json.put("code","200");
        json.put("msg","获取成功");
        return json;
    }

    @Anonymous
    @ResponseBody
    @RequestMapping(value ="/sentenceList",method = RequestMethod.POST)
    public JSONObject getSentenceList(HttpServletRequest request, HttpServletResponse response){
        Sentence sentence  = new Sentence();
        List<Sentence> list = sentenceService.selectSentenceList(sentence);

        JSONObject json1  = new JSONObject();
        JSONObject json  = new JSONObject();
        json1.put("sentenceList",list);
        json.put("list",json1);
        json.put("code","200");
        json.put("msg","获取成功");
        return json;
    }

    /**
     * 根据id获取用户回答详细信息
     */
    @PostMapping("/getUser")
    public AjaxResult getInfoById(@RequestBody JSONObject jsonObject)
    {
        String userName = jsonObject.get("currentUserName").toString();
        UserAnswer userAnswer = userAnswerService.selectUserAnswerByUserName(userName);

        //获取题目总数
        Question question = new Question();
        int questionCount = questionService.selectQuestionList(question).size();

        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("userAnswer", userAnswer);
        ajaxResult.put("questionCount", questionCount);
        return ajaxResult;
    }

    /**
     * 新增留言记录
     */
    @PostMapping("/addMessage")
    public AjaxResult addMessage(@RequestBody JSONObject jsonObject) {
        String userName = jsonObject.get("currentUserName").toString();
        String message = jsonObject.get("currentMessage").toString();

        Message userMessage = new Message();
        userMessage.setUserName(userName);
        userMessage.setMessage(message);
        userMessage.setCreateTime(new Date());

        messageService.insertMessage(userMessage);

        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("userMessage", userMessage);
        return ajaxResult;
    }

    /**
     * 新增用户记录
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody JSONObject jsonObject) {
        /** 储存用户 */
        String userName = jsonObject.get("currentUserName").toString();  //获取题目id

        /** 储存用户 */
        UserAnswer userAnswer = new UserAnswer();

        //初始化用户
        userAnswer.setUserName(userName);
        userAnswer.setCorrectQuestionIds("0");
        userAnswer.setCorrectCount(0);
        userAnswer.setStatus(0);

        userAnswerService.insertUserAnswer(userAnswer);

        /** 获取用户做的题目 */
        String currentQuestionId = jsonObject.get("questionId").toString();  //获取题目id

        /** 获取用户信息 */
        String currentUserName = userAnswer.getUserName();
        UserAnswer userAnswerToGetId = userAnswerService.selectUserAnswerByUserName(currentUserName);
        Long currentUserIdL = userAnswerToGetId.getId();

        String currentUserAnswer = jsonObject.get("userAnswer").toString();  //获取用户的回答


        /** 进行做题判断 */
        int results = doTheQuestion(currentQuestionId, userName, currentUserAnswer); //将问题id，用户id，用户回答给到做题模块

        UserAnswer currentUser = userAnswerService.selectUserAnswerById(currentUserIdL);

        /** 向前端返回数据 */
        String txt = "";
        if (results == 1) {
            /** 回答正确返回success */
            txt = "success";
        } else {
            /** 回答错误返回error */
            txt = "error";
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("currentUser", currentUser);
        ajaxResult.put("flag", txt);
        return ajaxResult;
    }

    /**
     * 修改用户信息
     */
    @Anonymous
    @PutMapping
    public AjaxResult edit(@RequestBody JSONObject jsonObject)
    {
        /** 获取用户做的题目 */
        String currentQuestionId = jsonObject.get("questionId").toString();  //获取题目id
        /** 获取用户信息 */
        String currentUserName = jsonObject.get("currentUserName").toString();  //获取用户名

        String currentUserAnswer = jsonObject.get("userAnswer").toString();  //获取用户的回答

        System.out.println("开始做题模块判断");
        /** 进行做题判断 */
        int results = doTheQuestion(currentQuestionId, currentUserName, currentUserAnswer); //将问题id，用户名，用户回答给到做题模块

        System.out.println("做题模块判断完成");
        UserAnswer currentUser = userAnswerService.selectUserAnswerByUserName(currentUserName);

        /** 向前端返回数据 */
        String txt = "";
        if (results == 1) {
            /** 回答正确返回success */
            txt = "success";
        } else {
            /** 回答错误返回error */
            txt = "error";
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("currentUser", currentUser);
        ajaxResult.put("flag", txt);
        return ajaxResult;
    }

    /**
     * 传输题目信息
     */
    @PostMapping("/getQuestionInfo")
    public AjaxResult getQuestionInfo(@RequestBody JSONObject jsonObject)
    {
        /** 获取用户做的题目 */
        String currentQuestionId = jsonObject.get("questionId").toString();  //获取题目id
        Long currentQuestionIdL = Long.parseLong(currentQuestionId);   //将String类型转化为Long类型
        Question currentQuestion = questionService.selectQuestionById(currentQuestionIdL);  //从题库里找到题目

        /** 向前端传送题目数据 */
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("currentQuestion", currentQuestion);
        return ajaxResult;
    }

    /**
     * 做题模块
     */
    public int doTheQuestion(String currentQuestionId, String currentUserName, String currentUserAnswer){
        /** 从题目库中获取题目信息 */
        Long currentQuestionIdL = Long.parseLong(currentQuestionId);   //将String类型转化为Long类型
        Question currentQuestion = questionService.selectQuestionById(currentQuestionIdL);

        /** 从用户库中获取用户信息 */
        UserAnswer currentUser = userAnswerService.selectUserAnswerByUserName(currentUserName);

        /** 判断用户是否需要初始化,以及防止空指针异常 */
        //使用异常来捕捉空指针异常
        try{
            Integer s = currentUser.getStatus();
            int uQ = currentUser.getCorrectCount();
            String uQI = currentUser.getCorrectQuestionIds();
        }catch (NullPointerException e){
            /** 初始化用户 */
            currentUser.setStatus(0);
            currentUser.setCorrectCount(0);
            currentUser.setCorrectQuestionIds("0");
        }

        /** 判断问题对错 */
        String questionAnswer = currentQuestion.getAnswer();   //获取正确的答案
        if(currentUserAnswer.equals(questionAnswer)){
            /** 回答正确 */
            /**  判断问题是否正确回答过 */
            String[] st = currentUser.getCorrectQuestionIds().split(",");
            boolean answer = false;
            for (String p : st) {
                if (p.equals(currentQuestionId)) {
                    /** 问题已被正确回答过 */
                    answer = true;
                    break;
                }
            }
            if (!answer){
                //问题未被回答过
                /** 储存正确回答的问题的id */
                currentUser.setCorrectQuestionIds(currentQuestionId + ',' + currentUser.getCorrectQuestionIds());
                /** 统计正确回答数量 */
                currentUser.setCorrectCount(currentUser.getCorrectCount() + 1);  //添加正确回答的数量

                //获取题目总数
                Question question = new Question();
                int questionCount = questionService.selectQuestionList(question).size();

                /** 判断是否完成题目*/
                if(currentUser.getCorrectCount() == questionCount ){
                    currentUser.setStatus(1); //通关
                }
                /** 将数据写入数据库 */
                userAnswerService.updateUserAnswer(currentUser);
            }
            return 1;
        }
        return 0;

    }
}
//    未使用的cookie
//    /** 判断是否要添加用户 */
//    Cookie[] cookies = request.getCookies();
//    Cookie cookie = CookieUtils.getCookie(cookies, currentUserIdL);
//
//    /** 重置用户id列表 */
//    String userIds = "";
//
///** 判断cookie是否为空 */
//        if(null != cookie){
//                /**
//                 * cookie不为空
//                 */
//
//                /** 从cookie中获取用户id数组（或者字符串） */
//                userIds = cookie.getValue();
//
//                /** 判断记录中储存cookie的个数是否大于1 */
//                if (userIds.indexOf("#")>0) {
//
//                /** 判断该用户id是否存在 */
//                String[] str = userIds.split("#");
//                boolean flag = false;
//                for (String s : str) {
//                if (s.equals(currentUserId)) {
//                /** 用户id已存在 */
//                flag = true;
//                break;
//                }
//                }
//                if (!flag) {
//                /**
//                 * 用户id不存在
//                 * 添加用户
//                 */
//                userIds = currentUserId + '#' + userIds;  //将用户id存进id列表
//                userAnswer.setUserName(jsonObject.get("").toString());    //获取用户的用户名并储存
//                cookie = new Cookie(userAnswer.getUserName(), userIds);
//                response.addCookie(cookie);
//
//                /** 储存用户 */
//                //初始化用户
//                userAnswer.setCorrectQuestionIds("0");
//                userAnswer.setCorrectCount(0);
//                userAnswer.setStatus(0);
//                //初始化内容已修改在答题模块，本因在新增用户内，但cookie问题未解决
//
//                userAnswerService.insertUserAnswer(userAnswer);
//                }
//                } else {
//                /**
//                 * 储存个数等于1
//                 * 判断该用户名的用户id是否相同
//                 */
//                if (!userIds.equals(currentUserId)){
//                /** 不相同则添加用户 */
//                userIds = currentUserId + '#' + userIds;  //将用户id存进id列表
//                userAnswer.setUserName(jsonObject.get("").toString());    //获取用户的用户名并储存
//                cookie = new Cookie(userAnswer.getUserName(), userIds);
//                response.addCookie(cookie);
//
//                /** 储存用户 */
//                //初始化用户
//                userAnswer.setCorrectQuestionIds("0");
//                userAnswer.setCorrectCount(0);
//                userAnswer.setStatus(0);
//
//                userAnswerService.insertUserAnswer(userAnswer);
//                }
//                }
//                } else{
//                /**
//                 * cookie为空
//                 * 添加cookie
//                 * */
//                userIds = currentUserId;  //将用户id存进id列表
//                userAnswer.setUserName(jsonObject.get("").toString());    //获取用户的用户名并储存
//                cookie = new Cookie(userAnswer.getUserName(), userIds);
//                response.addCookie(cookie);
//
//                /** 储存用户 */
//                //初始化用户
//                userAnswer.setCorrectQuestionIds("0");
//                userAnswer.setCorrectCount(0);
//                userAnswer.setStatus(0);
//                //初始化内容已修改在答题模块，本因在新增用户内，但cookie问题未解决
//
//                userAnswerService.insertUserAnswer(userAnswer);
//                }